<?php
$page_title = '填报监考意愿 - 考务管理系统';

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 数据库连接
try {
    require_once 'database.php';
    $db_connected = isset($conn) && $conn instanceof mysqli;
} catch (Exception $e) {
    error_log("数据库连接失败: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 检查用户是否为在职员工
$user_id = $_SESSION['user_id'];
$serving_check_sql = "SELECT serving FROM staff WHERE user_id = ?";
$serving_stmt = $conn->prepare($serving_check_sql);
$serving_stmt->bind_param('s', $user_id);
$serving_stmt->execute();
$serving_result = $serving_stmt->get_result();

if ($serving_result->num_rows === 0 || !$serving_result->fetch_assoc()['serving']) {
    $_SESSION['error_message'] = "该账号非在职员工，请联系管理员";
    header('Location: logout.php');
    exit();
}

// 处理监考意愿提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_intention'])) {
    $exam_id = intval($_POST['exam_id'] ?? 0);
    $intention = $_POST['intention'] === 'accept' ? 1 : 0;

    if ($exam_id > 0) {
        try {
            // 检查考试项目是否存在
            $exam_check_sql = "SELECT exam_name FROM exams WHERE id = ?";
            $exam_check_stmt = $conn->prepare($exam_check_sql);
            $exam_check_stmt->bind_param('i', $exam_id);
            $exam_check_stmt->execute();
            $exam_check_result = $exam_check_stmt->get_result();

            if ($exam_check_result->num_rows > 0) {
                $exam_data = $exam_check_result->fetch_assoc();
                $exam_name = $exam_data['exam_name'];

                $conn->begin_transaction();

                // 检查是否已经填报过
                $check_sql = "SELECT id FROM signups_leaves WHERE exam_id = ? AND user_id = ?";
                $check_stmt = $conn->prepare($check_sql);
                $check_stmt->bind_param('is', $exam_id, $user_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();

                if ($check_result->num_rows > 0) {
                    // 更新现有记录
                    $update_sql = "UPDATE signups_leaves SET signup_intention = ?, signup_time = CURRENT_TIMESTAMP WHERE exam_id = ? AND user_id = ?";
                    $update_stmt = $conn->prepare($update_sql);
                    $update_stmt->bind_param('iis', $intention, $exam_id, $user_id);
                    $update_stmt->execute();
                } else {
                    // 插入新记录
                    $insert_sql = "INSERT INTO signups_leaves (exam_id, exam_name, user_id, user_name, signup_intention) VALUES (?, ?, ?, ?, ?)";
                    $insert_stmt = $conn->prepare($insert_sql);
                    $user_name = $_SESSION['username'];
                    $insert_stmt->bind_param('isssi', $exam_id, $exam_name, $user_id, $user_name, $intention);
                    $insert_stmt->execute();
                }

                $conn->commit();
                $success_message = $intention ? "已成功填报：希望参加监考" : "已成功填报：拒绝参加监考";

            } else {
                $error_message = "考试项目不存在";
            }
        } catch (Exception $e) {
            if ($conn->inTransaction()) {
                $conn->rollback();
            }
            $error_message = "填报失败: " . $e->getMessage();
        }
    } else {
        $error_message = "无效的考试项目";
    }
}

// 获取考试项目
$exams_sql = "SELECT id, exam_name, exam_date, subject_count, students_per_subject, created_at FROM exams ORDER BY exam_date ASC";
$exams_result = $conn->query($exams_sql);

// 获取当前用户的监考意愿
$intentions = [];
if ($exams_result && $exams_result->num_rows > 0) {
    $exam_ids = [];
    $exams_result->data_seek(0);
    while ($row = $exams_result->fetch_assoc()) {
        $exam_ids[] = $row['id'];
    }

    if (!empty($exam_ids)) {
        $placeholders = implode(',', array_fill(0, count($exam_ids), '?'));
        $intentions_sql = "SELECT exam_id, signup_intention, signup_time FROM signups_leaves WHERE user_id = ? AND exam_id IN ($placeholders)";
        $intentions_stmt = $conn->prepare($intentions_sql);
        $types = 's' . str_repeat('i', count($exam_ids));
        $intentions_stmt->bind_param($types, $user_id, ...$exam_ids);
        $intentions_stmt->execute();
        $intentions_result = $intentions_stmt->get_result();

        while ($row = $intentions_result->fetch_assoc()) {
            $intentions[$row['exam_id']] = [
                'intention' => $row['signup_intention'],
                'time' => $row['signup_time']
            ];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">
</head>
<body>
<!-- 导航栏 -->
<?php include_once 'common/navigation.php'; ?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="card">
        <div class="page-header">
            <h1 class="page-title">填报监考意愿</h1>
            <p class="page-subtitle">查看考试项目，提交您的监考意愿</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success fade-in">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
        </div>
    <?php elseif (isset($error_message)): ?>
        <div class="alert alert-danger fade-in">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
        </div>
    <?php endif; ?>

    <!-- 考试项目列表 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-clipboard-list"></i> 考试项目列表
        </div>
        <div class="card-body">
            <?php if ($exams_result && $exams_result->num_rows > 0): ?>
                <div class="table-container">
                    <table class="table">
                        <thead>
                        <tr>
                            <th><i class="fas fa-graduation-cap"></i> 考试项目名称</th>
                            <th><i class="fas fa-calendar"></i> 考试日期</th>
                            <th><i class="fas fa-book"></i> 科目数量</th>
                            <th><i class="fas fa-users"></i> 学生数/科目</th>
                            <th><i class="fas fa-heart"></i> 监考意愿</th>
                            <th><i class="fas fa-clock"></i> 填报时间</th>
                            <th><i class="fas fa-cogs"></i> 操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $exams_result->data_seek(0);
                        while($exam = $exams_result->fetch_assoc()):
                            $exam_id = $exam['id'];
                            $has_intention = isset($intentions[$exam_id]);
                            $intention_status = $has_intention ?
                                ($intentions[$exam_id]['intention'] ? '希望参加' : '拒绝参加') : '未填报';
                            $intention_time = $has_intention ? $intentions[$exam_id]['time'] : '';
                            ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($exam['exam_name']); ?></strong>
                                </td>
                                <td><?php echo htmlspecialchars($exam['exam_date'] ?? '未设定'); ?></td>
                                <td>
                                            <span class="badge badge-info">
                                                <?php echo htmlspecialchars($exam['subject_count'] ?? '0'); ?>
                                            </span>
                                </td>
                                <td>
                                            <span class="badge badge-success">
                                                <?php echo htmlspecialchars($exam['students_per_subject'] ?? '0'); ?>
                                            </span>
                                </td>
                                <td>
                                    <?php if ($has_intention): ?>
                                        <?php if ($intentions[$exam_id]['intention']): ?>
                                            <span class="badge badge-success">
                                                        <i class="fas fa-check"></i> 希望参加
                                                    </span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">
                                                        <i class="fas fa-times"></i> 拒绝参加
                                                    </span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="badge badge-warning">
                                                    <i class="fas fa-question"></i> 未填报
                                                </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($intention_time): ?>
                                        <small class="text-muted">
                                            <?php echo date('Y-m-d H:i', strtotime($intention_time)); ?>
                                        </small>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="d-flex gap-2">
                                        <form method="post" style="display: inline;" onsubmit="return confirmSubmission(this, '希望参加')">
                                            <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                                            <input type="hidden" name="intention" value="accept">
                                            <input type="hidden" name="submit_intention" value="1">
                                            <button type="submit" class="btn btn-success btn-sm">
                                                <i class="fas fa-thumbs-up"></i> 希望参加
                                            </button>
                                        </form>

                                        <form method="post" style="display: inline;" onsubmit="return confirmSubmission(this, '拒绝参加')">
                                            <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                                            <input type="hidden" name="intention" value="reject">
                                            <input type="hidden" name="submit_intention" value="1">
                                            <button type="submit" class="btn btn-danger btn-sm">
                                                <i class="fas fa-thumbs-down"></i> 拒绝参加
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center py-5">
                    <div class="mb-3">
                        <i class="fas fa-clipboard-list" style="font-size: 48px; color: #6c757d;"></i>
                    </div>
                    <h4 class="text-muted">暂无考试项目</h4>
                    <p class="text-muted">目前没有可填报监考意愿的考试项目</p>
                    <a href="user_home.php" class="btn btn-primary">
                        <i class="fas fa-home"></i> 返回首页
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- 填报说明 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-info-circle"></i> 填报说明
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-thumbs-up text-success"></i> 希望参加
                            </span>
                        <span class="info-value">
                                表示您愿意参与该考试项目的监考工作
                            </span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-thumbs-down text-danger"></i> 拒绝参加
                            </span>
                        <span class="info-value">
                                表示您不希望参与该考试项目的监考工作
                            </span>
                    </div>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-md-6">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-edit text-warning"></i> 修改意愿
                            </span>
                        <span class="info-value">
                                您可以随时修改自己的监考意愿
                            </span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-clock text-info"></i> 填报时间
                            </span>
                        <span class="info-value">
                                系统将记录您每次填报的时间
                            </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 确认提交监考意愿
    function confirmSubmission(form, action) {
        const examName = form.closest('tr').querySelector('strong').textContent;
        const message = `确定要提交"${action}"意愿吗？\n\n考试项目：${examName}\n\n提交后可以随时修改。`;

        return confirm(message);
    }

    // 防止重复提交
    document.addEventListener('DOMContentLoaded', function() {
        const forms = document.querySelectorAll('form');

        forms.forEach(form => {
            form.addEventListener('submit', function() {
                const submitBtn = this.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.disabled = true;
                    const originalText = submitBtn.innerHTML;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';

                    // 5秒后重新启用按钮
                    setTimeout(() => {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }, 5000);
                }
            });
        });
    });

    // 表格行悬停效果
    document.addEventListener('DOMContentLoaded', function() {
        const tableRows = document.querySelectorAll('.table tbody tr');

        tableRows.forEach(row => {
            row.addEventListener('mouseenter', function() {
                this.style.backgroundColor = 'rgba(13, 110, 253, 0.05)';
            });

            row.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
            });
        });
    });
</script>

<?php
// 关闭数据库连接
if (isset($conn)) {
    $conn->close();
}
?>
</body>
</html>